package com.van.utils;

import java.security.MessageDigest;

/**
 * @author VanKa qq:2395073039
 * @date 2021/6/9 16:59
 */
public class MD5Util {

    private static final String hexDigits[] = {"0", "1", "2", "3", "4", "5",
            "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"};

    /**
     * 字节数组 转换成 16进制字符串
     * @param b byte[]
     * @return String
     */
    private static String byteArrayToHexString(byte[] b) {
        StringBuilder resultSb = new StringBuilder();
        for (int i = 0; i < b.length; i++)
            resultSb.append(byteToHexString(b[i]));

        return resultSb.toString();
    }
    /**
     * 字节 转换成 16进制字符串
     * @param b byte
     * @return String
     */
    private static String byteToHexString(byte b) {
        int n = b;
        if (n < 0)
            n += 256;
        int d1 = n / 16;
        int d2 = n % 16;
        return hexDigits[d1] + hexDigits[d2];
    }

    /**
     * 加密
     * @param origin 需要加密的字符串
     * @param charSetName 盐
     * @return 密文
     */
    public static String MD5Encode(String origin, String charSetName) {
        String resultString = origin + charSetName;
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            resultString = byteArrayToHexString(md.digest(resultString.getBytes()));
        } catch (Exception exception) {

        }
        return resultString;
    }
}
